<template>
  <div class="markaided_all" ref="container" :id="id">
    <div class="markaid_center">

      <div v-show="modalshow" @pointerdown.stop="{}" class="showtree">
        <div class="yingcangtree"></div>
        <div style="width:100%;height:calc(100% - 50px);float:left;overflow:auto">
          <el-tree ref="catalogMLTree" highlight-current render-after-expand node-key='id' default-expand-all
                   :data="catalogML" :props="catalogProps" v-if="catalogML&&catalogML.length" style="width:100%">
          </el-tree>
        </div>
        <el-button style="float:right;margin:5px 10px 0 0" size="small" type="plain" @click="cancelAddMindMapping">
          取消
        </el-button>
        <el-button style="float:right;margin:5px 10px 0 0" size="small" type="primary" @click="addMindMapping">确认
        </el-button>
      </div>

      <div v-show="showBookmarkList" @pointerdown.stop="{}" class="bookmarkList">
        <!-- <div class="button" @click="addBookmark('',$event)">添加书签</div> -->
        <div class="bookmarks">
          <div v-for="item in bookmarks" v-if="item.bmid!==item.bmtype&&item.bmtype===moduleSwitch"
               @click="openBookmark(item)">
            {{item.bmname}}
            <span class="edit" title="编辑书签" @click="editBookmark(item,$event)"></span>
            <span class="del" title="删除书签" @click="deleteBookmark(item,$event)"></span>
          </div>
        </div>
      </div>

      <resize-by-drag class="resize_by_drag" ref="resizeLayout" :init-page-data.sync="pageData">
        <div slot="container_left">
          <div class="slot_item">
            <div class="nav">
              <span class="word14" :class="{select_show_type:moduleSwitch==='dossier'}"
                    @click="switchModule('dossier')">电子卷宗</span>
              <span class="word14" :class="{select_show_type:moduleSwitch==='docDossier'}"
                    @click="switchModule('docDossier')">文书卷宗</span>
            </div>
            <div style="width: 100%;height: calc(100% - 25px);">

              <div style="width: 100%;height: 100%" v-show="moduleSwitch==='dossier'">

                <dossier-tree
                  ref="dossierTree"
                  :show-contextmenu="false"
                  :shift-command="false"
                  :ctrl-command="false"
                  :show-delete="false"
                  @node-click="nodeClick"
                  @rootNodeChanged="rootNodeChange"></dossier-tree>

                <!--<el-input placeholder="输入关键字进行检索" size="mini" style="width:calc(100% - 20px);margin:5px 10px;font-size: 14px" v-model="filterText">-->
                <!--</el-input>-->
                <!--<el-tree class="dossierTree" node-key='NodeID' ref="dossierTree" :render-after-expand="false" :expand-on-click-node="true" :highlight-current="true" :auto-expand-parent="true" :data="dossierTreeDataSource" :render-content="renderContent" :filter-node-method="filterNode" @node-click="nodeClick">-->
                <!--</el-tree>-->
              </div>
              <div class="markaid_book" v-show="moduleSwitch==='docDossier'">
                <el-input placeholder="输入关键字进行检索" size="mini"
                          style="width:calc(100% - 20px);margin:5px 10px;font-size: 14px" v-model="filterText">
                </el-input>
                <el-tree class="dossierTree" node-key='NodeID' ref="docDossierTree"
                         :render-after-expand="false" :expand-on-click-node="false"
                         :highlight-current="true" :auto-expand-parent="true"
                         :data="docDossierTreeDataSource" :render-content="renderContent"
                         :filter-node-method="filterNode" @node-click="nodeClick">
                </el-tree>
              </div>
            </div>
          </div>
        </div>
        <div slot="container_right">
          <div class="slot_item">
            <div class="markaid_cl" @mousedown="pdfMouseMove">
              <div style="width:100%;height:100%;margin: 0 auto;">
                <pre-zjcl class="PreZjcl" @pdf_callback="pdf_callback" :config="config" ref="PreZjcl"></pre-zjcl>
                <!--<c-pdf ref="pdfjs" @fullscreen="fullscreen" :fullscreen="true" class="pdfview"></c-pdf>-->
              </div>
              <div class="markaid_f_limg" @click="currPage('prev')"></div>
              <div class="markaid_f_rimg" @click="currPage('next')"></div>
            </div>
            <div class="right_item" style="right: 95px;" :class="{active_right_item:showBookmarkList}"
                 @click="bookList">
              书签
            </div>
            <div class="right_item" :class="{active_right_item:modalshow}" @click="zjclTree">
              ＋加入证据
            </div>
          </div>
        </div>
      </resize-by-drag>

    </div>
  </div>
</template>
<script>
  import {mapState, mapGetters} from 'vuex'
  import commonServer from '../server/common/commonServer'
  import evidenceCatalogTree from '../config/evidenceCatalogTree'

  let quantity = require('../common/quantity')

  let {action, mutation} = quantity

  const {util: {getRandomId}} = require('../util')

  let pageData = {
    name: 'outer',
    isHorizontal: true,
    showBar: true,
    bar: {
      style: {
        height: '100%',
        width: '30px',
        background: '#e0f5fb',
        'text-align': 'center',
        'border-right': '1px solid #a4d3ed',
        display: 'inline-block'
      },
      options: {
        buttonList: [
          {
            name: 'container_left',
            innerText: '',
            innerHTML: '示<br>证<br>大<br>纲'
          },
          {
            name: 'container_right',
            innerText: '',
            innerHTML: '卷<br>宗'
          }
        ],
        buttonStyle: {
          'border-top': '0.5px #a4d3ed solid',
          'border-bottom': '0.5px #a4d3ed solid',
          height: '115px',
          display: 'block',
          'font-size': '14px',
          background: '#e0f5fb',
          color: '#0b609c'
        },
        buttonHoverStyle: {
          background: '#3787c1',
          color: '#fff',
          cursor: 'pointer'
        },
        position: 'left'
      }
    },
    hideButton: {
      style: {
        width: '18px',
        height: '18px',
        display: 'inline-block',
        position: 'absolute',
        background:
          'url(\'\') no-repeat',
        top: '12px',
        right: '12px',
        cursor: 'pointer',
        'z-index': '99999'
      },
      options: {
        innerText: ''
        // innerHTML: "<i class=\"iconfont\">&#xe6d5;</i>"
      }
    },
    line: {
      style: {
        height: '100%',
        width: '10px',
        'vertical-align': 'top',
        display: 'inline-block',
        position: 'relative'
      },
      controlButtonStyle: {
        'text-align': 'center',
        'vertical-align': 'center',
        background:
          'url(\'\')',
        height: '25px',
        width: '10px',
        margin: 'auto',
        position: 'absolute',
        cursor: 'col-resize',
        top: 0,
        left: 0,
        bottom: 0,
        right: 0
      },
      options: {}
    },
    slots: [
      {
        name: 'container_left',
        style: {
          height: '100%',
          width: '161px',
          'vertical-align': 'top',
          // "min-width": "250px",
          display: 'inline-block',
          overflow: 'hidden',
          position: 'relative'
        },
        options: {
          showHideButton: false,
          titleText: '最左边的',
          ratio: 0.3,
          hide: false
        }
      },
      {
        name: 'container_right',
        style: {
          height: '100%',
          width: '167px',
          'vertical-align': 'top',
          'min-width': '500px',
          display: 'inline-block',
          overflow: 'hidden',
          position: 'relative'
        },
        options: {
          showHideButton: false,
          titleText: '最右边的',
          ratio: 0.7,
          hide: false
        }
      }
    ],
    title: {
      style: {
        overflow: 'hidden',
        'white-space': 'nowrap',
        'text-overflow': 'ellipsis'
      }
    }
  }

  let moduleSwitch = {
    dossier: 'dossier',
    docDossier: 'docDossier'
  }

  export default {
    name: 'MarkingAided',
    data () {
      return {
        id: getRandomId(),
        catalogProps: {
          children: 'children',
          label: 'alias'
        },
        moduleSwitch: moduleSwitch.dossier,
        modalshow: false,
        showBookmarkList: false,
        fileDataSourceIndex: 0,
        docFileDataSourceIndex: 0,
        filterText: '',
        pageData: {},
        firstLoad: true,
        config: {
          fullscreen: true,
          collect: true,
          nodeid: ''
        },
        catalogML: []
      }
    },
    computed: {
      ...mapState({
        isMaxWindow: state => state.container.isMaxWindow,
        fullScreen: state => state.container.fullScreen,
        dossierTreeDataSource: state => state.appearCourt.dossierTreeDataSource,
        docDossierTreeDataSource: state =>
          state.appearCourt.docDossierTreeDataSource,
        dossierDataSource: state => state.appearCourt.dossierDataSource,
        evidenceCatalogTreeData: state => state.preplan.evidenceCatalogTreeData,
        bookmarks: state => state.bookmark.bookmarks,
        historys: state => state.bookmark.historys
      }),
      ...mapGetters({
        fileDataSource: 'fileDataSource',
        docFileDataSource: 'docFileDataSource'
        // catalogML: "catalogML"
      })
    },
    created () {
      this.pageData = pageData
    },
    watch: {
      filterText (newVal, oldVal) {
        this.$refs[this.moduleSwitch + 'Tree'].filter(newVal)
      }
    },
    methods: {
      bookList () {
        this.showBookmarkList = !this.showBookmarkList
        this.modalshow = false

        this.windowsAddEventListener('pointerdown', this.hideModal)
        window.addEventListener('blur', this.hideModal)
      },
      zjclTree () {
        this.modalshow = !this.modalshow
        if (this.modalshow) {
          this.catalogML = evidenceCatalogTree.getCatalogML()
        }
        this.showBookmarkList = false

        this.windowsAddEventListener('pointerdown', this.hideModal)
        window.addEventListener('blur', this.hideModal)
      },
      hideModal (ev) {
        this.modalshow = false
        this.showBookmarkList = false

        this.windowsRemoveEventListener('pointerdown', this.hideModal)
        window.removeEventListener('blur', this.hideModal)
      },
      async pdf_callback ({eventName, data = {}}) {
        console.log('pdf_callback', eventName, data)
        if (eventName === 'fullscreen') {
          this.fullscreen()
        } else if (eventName === 'collect') {
          if (data.bookmark.bmid) {
            await this.deleteBookmark(data.bookmark)
          } else {
            console.log(data)
            await this.addBookmark(data.nodeid)
          }
        }
      },
      async deleteBookmark (bookmark, ev) {
        if (ev) ev.stopPropagation()
        console.log(bookmark)
        await this.$store.dispatch(action.bookmark.deleteBookmark, bookmark.bmid)
      },
      async editBookmark (bookmark, ev) {
        if (ev) ev.stopPropagation()

        // 检查书签是否已存在
        let item = this.bookmarks.find(item => item.bmid === bookmark.bmid)

        item = JSON.parse(JSON.stringify(item))

        try {
          let res = await this.$prompt('请输入书签名', '修改书签', {
            showClose: false,
            closeOnPressEscape: false,
            inputValue: item.bmname,
            inputValidator: value => {
              if (value.trim().length) return true
              return '书签名不能为空'
            }
          })

          item.bmname = res.value

          let result = await this.$store.dispatch(
            action.bookmark.saveBookmark,
            item
          )

          if (result) this.$message({message: '书签修改成功', type: 'success'})
        } catch (e) {
        }
      },
      async addBookmark (node, ev) {
        if (ev) ev.stopPropagation()

        let srcTree = this.$refs[this.moduleSwitch + 'Tree']

        if (typeof node === 'string') {
          node = srcTree.getNode(node)
          if (node) node = node.data
        }

        console.log(node)

        node = node || srcTree.getCurrentNode()

        // 检查书签是否已存在
        let item = this.bookmarks.find(
          item => item.nodeid === node.NodeID && item.bmid !== item.bmtype
        )

        let cjsj = ''
        let bmid = ''

        if (item) {
          cjsj = item.cjsj
          bmid = item.bmid
        }

        try {
          let res = await this.$prompt(
            '请输入书签名',
            bmid ? '修改书签' : '添加新书签',
            {
              showClose: false,
              closeOnPressEscape: false,
              inputValue: bmid ? item.bmname : node.MLXSMC,
              inputValidator: value => {
                if (value.trim().length) return true
                return '书签名不能为空'
              }
            }
          )

          let nodeid = node.NodeID
          let bmname = res.value
          let bmtype = this.moduleSwitch

          await this.$store.dispatch(action.bookmark.saveBookmark, {
            bmid,
            rootid: srcTree.currDossierID || '',
            nodeid,
            bmname,
            bmtype,
            cjsj
          })

          // if (result) this.$message({ message: "书签已保存", type: "success" });
        } catch (e) {
        }
      },
      switchModule (moduleSwitch) {
        this.moduleSwitch = moduleSwitch
        // this.firstLoad = true;
        this.showPdf()
        this.filterText = ''
        this.$refs[this.moduleSwitch + 'Tree'] &&
        this.$refs[this.moduleSwitch + 'Tree'].filter()
      },
      fullscreen () {
        if (this.isMaxWindow === this.fullScreen) {
          this.window_control('max', this.isMaxWindow)
        }
        this.$store.commit(mutation.container.fullScreen)
      },
      renderContent (h, {node, data, store}) {
        return (
          <span class={'node_' + data.ID} style="font-size:14px">
            {data.MLXSMC}
          </span>
        )
      },
      filterNode (value, data, node) {
        if (!value) return true
        if (node.level > 1 && node.parent.visible) return true
        return data.MLXSMC.indexOf(value) !== -1
      },
      nodeClick (data, node) {
        let index = this[this.moduleSwitch === moduleSwitch.dossier ? 'fileDataSource' : 'docFileDataSource'].findIndex(item => item.ID === data.ID)
        if (index === -1) return console.log('数据源里没有')
        this[this.moduleSwitch === moduleSwitch.dossier ? 'fileDataSourceIndex' : 'docFileDataSourceIndex'] = index
        this.expandNode(data.NodeID)
        this.showPdf()
      },
      /**
       * 根据id展开自身及父节点
       */
      expandNode (id) {
        let node = this.$refs[this.moduleSwitch + 'Tree'].getNode(id)
        if (!node) return
        let _node = node
        _node.expand()
        while ((_node = _node.parent)) {
          _node.expand()
        }
      },
      async openBookmark (bookmark) {
        let tree = this.$refs[this.moduleSwitch + 'Tree']
        if (bookmark.rootid) {
          await tree.loadTreeData(bookmark.rootid)
        }
        this.$nextTick(() => {
          this.setSelectedNode(bookmark.nodeid)
        })
      },
      setSelectedNode (id) {
        let node = this.$refs[this.moduleSwitch + 'Tree'].getNode(id)
        if (!node) return console.log('没有该节点', id)
        this.nodeClick(node.data, node)

        let el = document.querySelector(`#${this.id} .node_${id}`)
        this.$nextTick(() => {
          el &&
          el.scrollIntoView({
            behavior: 'smooth',
            block: 'nearest',
            inline: 'nearest'
          })
          // el && el.scrollIntoView();
        })
      },
      useMouseMove (e) {
        let x = e.clientY
        // let imgTemplate = this.$refs.imgContainer
        let scrollContainer = this.$refs.scrollContainer
        scrollContainer.onmousemove = ev => {
          if (x > ev.clientY) {
            scrollContainer.scrollTop += x - ev.clientY
          } else if (x < ev.clientY) {
            scrollContainer.scrollTop -= ev.clientY - x
          }
          x = ev.clientY
        }
        scrollContainer.onmouseup = () => {
          scrollContainer.onmouseup = scrollContainer.onmousemove = null
        }
        scrollContainer.onmouseout = () => {
          scrollContainer.onmouseout = scrollContainer.onmousemove = null
        }
      },
      pdfMouseMove (e) {
      },
      rootNodeChange (nodeid) {
        if (!this.fileDataSource.length) return
        this.$nextTick(() => {
          this.setSelectedNode(this.fileDataSource[0].NodeID)
        })
      },
      async currPage (type) {
        let index = this.moduleSwitch === moduleSwitch.dossier ? this.fileDataSourceIndex : this.docFileDataSourceIndex
        let rootID = this.moduleSwitch === moduleSwitch.dossier ? this.$refs.dossierTree.currDossierID : null

        if (type === 'prev') {
          if (this.$store.getters.isFirstNode(rootID, index - 1)) {
            return this.$message('当前已经是第一页')
          } else {
            this.fileDataSourceIndex = index--
          }
        } else {
          if (this.$store.getters.isLastNode(rootID, index + 1)) {
            return this.$message('当前已经是最后一页')
          } else {
            this.docFileDataSourceIndex = index++
          }
        }

        let nodeid = this[this.moduleSwitch === moduleSwitch.dossier ? 'fileDataSource' : 'docFileDataSource'][index].NodeID
        if (!nodeid) return
        this.setSelectedNode(nodeid)
      },
      // 显示当前选中的电子卷宗pdf
      async showPdf () {
        let node = {}
        if (this.firstLoad) {
          this.firstLoad = false

          let rootid = ''
          let nodeid = ''

          let dossierTime = new Date(this.historys.dossier.cjsj || 0).getTime()
          let docDossierTime = new Date(this.historys.docDossier.cjsj || 0).getTime()

          if (dossierTime >= docDossierTime) {
            this.moduleSwitch = moduleSwitch.dossier
            rootid = this.historys.dossier.rootid
            nodeid = this.historys.dossier.nodeid
          } else {
            this.moduleSwitch = moduleSwitch.docDossier
            rootid = this.historys.docDossier.rootid
            nodeid = this.historys.docDossier.nodeid
          }

          let tree = this.$refs[this.moduleSwitch + 'Tree']
          if (rootid) await tree.loadTreeData(rootid)

          this.$nextTick(() => {
            this.setSelectedNode(nodeid)
          })

          return
        }

        if (this.moduleSwitch === moduleSwitch.dossier) {
          node = this.fileDataSource[this.fileDataSourceIndex]
          if (node) this.$refs.dossierTree.setCurrentNode(node)
        } else if (this.moduleSwitch === moduleSwitch.docDossier) {
          node = this.docFileDataSource[this.docFileDataSourceIndex]
          if (node) this.$refs.docDossierTree.setCurrentNode(node)
        }
        if (!node) return
        let base64 = null

        if (process.browser) {
          base64 = await this.$api.post.getEvidenceMaterialByCode({
            fileID: node.NodeID,
            fileType: this.moduleSwitch === moduleSwitch.dossier ? 0 : 1,
            dbPath: this.$store.state.appearCourt.casePath
          })
        } else {
          base64 = await commonServer.getPDFFileByID(node.ID)
        }
        let nodeid = node.NodeID
        let bmtype = this.moduleSwitch
        this.config.nodeid = nodeid
        let srcTree = this.$refs[this.moduleSwitch + 'Tree']
        await this.$store.dispatch(action.bookmark.saveHistory, {
          rootid: srcTree.currDossierID || '',
          nodeid,
          bmtype
        })
        this.$refs.PreZjcl.show(base64)
      },
      cancelAddMindMapping () {
        this.$refs.catalogMLTree && this.$refs.catalogMLTree.setCurrentNode({})
        // this.modalshow = false;
        this.hideModal()
      },
      // 添加当前电子卷宗到思维导图
      addMindMapping () {
        let tree = this.$refs.catalogMLTree
        if (!tree) return
        let node = tree.getCurrentNode()
        tree.setCurrentNode({})
        if (!node) return this.$alert('没有选中节点', '提示')

        let srcTree = this.$refs[this.moduleSwitch + 'Tree']

        let transferData = []

        let cnode = srcTree.getCurrentNode()

        transferData.push(cnode)

        let _cnode = srcTree.getNode(cnode)
        if (_cnode.parent) {
          let pnode = _cnode.parent.data
          transferData.push(pnode)
        }

        let data = {node: node, dossiers: JSON.stringify(transferData)}

        this.$eventBus.$emit('ADD_FILES_INTO_CATALOG', data)

        this.modalshow = false
      }
    },
    async mounted () {
      try {
        this.showPdf()
      } catch (error) {
        console.error(error)
      }
    }
  }
</script>
<style scoped>
  .markaid_book {
    height: 100%;
  }

  .markaid_f_rimg,
  .markaid_f_limg {
    position: absolute;
    top: 50%;
    width: 55px;
    height: 55px;
    cursor: pointer;
    transform: translate(0, -50%);
    background-size: 100% 100% !important;
    opacity: 0.4;
  }

  .markaid_f_rimg:hover,
  .markaid_f_limg:hover {
    opacity: 1;
  }

  .markaid_f_rimg {
    right: 50px;
    background: url("~@/assets/img/yuan/pdfRight.png");
  }

  .markaid_f_limg {
    left: 50px;
    background: url("~@/assets/img/yuan/pdfLeft.png");
  }

  .markaid_cl {
    width: 100%;
    height: 100%;
    position: relative;
    imgtemplate-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.1);
  }

  .markaid_center {
    width: 100%;
    height: 100%;
  }

  .markaided_all {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .showtree,
  .bookmarkList {
    position: absolute;
    width: 260px;
    height: 50%;
    background: white;
    top: 34px;
    right: 1px;
    border: 1px solid #ddd;
    z-index: 999;
    border-radius: 2px;
  }

  .bookmarkList {
    width: 200px;
    height: 300px;
  }

  .bookmarkList > div.button {
    font-size: 14px;
    border-bottom: 1px solid #ccc;
    height: 30px;
    line-height: 30px;
    text-indent: 15px;
  }

  .bookmarkList > div.bookmarks {
    height: 100%;
    font-size: 14px;
    border-bottom: 1px solid #ccc;
    overflow-y: auto;
  }

  .bookmarkList > div.bookmarks > div {
    font-size: 14px;
    height: 30px;
    line-height: 30px;
    text-indent: 15px;
    position: relative;
    width: 100%;
  }

  .bookmarkList > div.button:hover,
  .bookmarkList > div.bookmarks > div:hover {
    background-color: #ccc;
  }

  .bookmarkList > div.bookmarks > div:hover .edit,
  .bookmarkList > div.bookmarks > div:hover .del {
    visibility: visible !important;
  }

  .bookmarkList .edit,
  .bookmarkList .del {
    height: 100%;
    width: 30px;
    display: inline-block;
    position: absolute;
    top: 0;
    background-position: center;
    background-repeat: no-repeat;
    visibility: hidden;
    cursor: pointer !important;
  }

  .bookmarkList .del {
    right: 0;
    background-image: url("~@/assets/img/delete.png");
  }

  .bookmarkList .edit {
    right: 30px;
    background-image: url("~@/assets/img/edit.png");
  }

  .yingcangtree {
    width: 100px;
    height: 1px;
    float: right;
    background: white;
    margin-top: -1px;
    margin-right: 11px;
  }

  .nav {
    height: 25px;
  }

  .nav span {
    height: 100%;
    width: 50%;
    display: inline-block;
    text-align: center;
    line-height: 25px;
    background-color: #e5f8ff;
    border-right: 1px solid #157ac2;
  }

  .nav span:hover {
    background-color: #157ac2;
    color: white;
  }

  .nav span:nth-last-child(1) {
    border-right: none;
  }

  .select_show_type {
    background-color: #157ac2 !important;
    color: white !important;
  }

  .dossierTree {
    height: calc(100% - 38px);
    width: 100%;
    overflow: auto;
  }

  .resize_by_drag {
    height: 100%;
  }

  .slot_item {
    height: 100%;
    width: 100%;
    overflow: hidden;
    border: 1px solid #bdd5e6;
    position: relative;
  }

  .right_item {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    padding: 0 10px;
    color: #157ac2;
    font-size: 15px !important;
    line-height: 32px;
  }

  .active_right_item,
  .right_item:hover {
    background: #9ed6f1;
  }

  .PreZjcl {
    height: 100%;
  }
</style>
